package de.gis;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.SharedPreferences;
import android.util.Log;

public class Uploader extends CouchCommunicator {

	private static final String TAG = "Uploader";

	private final DocumentDescription documentDescription;

	public Uploader(String dbUrl, SharedPreferences prefs,
			DocumentDescription documentDescription) {
		super(dbUrl, prefs);
		this.documentDescription = documentDescription;
	}

	public void doit() throws Exception {
		// use a time stamp as document id
		String id = "" + System.currentTimeMillis();
		String urlStr = dbUrl + id;
		String rev = createDocument(urlStr);
		createImageAttachment(urlStr, rev);
	}

	private String createDocument(String urlStr) throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		Log.d(TAG, "Creating new document at " + urlStr);
		HttpPut request = createHttpPut(urlStr);
		addJson(request,  documentDescription.toJson());
		HttpResponse response = httpclient.execute(request);

		if (response.getStatusLine().getStatusCode() == 403
				|| response.getStatusLine().getStatusCode() == 401) {
			throw new UnauthorizedException(true /* isLocal */);
		}

		HttpEntity entity = response.getEntity();
		String rev = "";
		if (entity != null) {
			String data = EntityUtils.toString(entity);
			JSONObject jo = new JSONObject(data);
			if (!jo.has("rev")) {
				throw new IOException(
						"Could not create document, couch replied " + data);
			}
			rev = jo.get("rev").toString();
			Log.d(TAG, "Created document with revision " + rev);
			return rev;
		} else {
			Log.d(TAG, "empty response");
			throw new IOException(
					"Could not create document, couch did not reply");
		}
	}

	private void createImageAttachment(String urlStr, String rev)
			throws IOException, ClientProtocolException {
		String attachmentUrl = urlStr + "/img.jpg?rev=" + rev;
		HttpPut request = createHttpPut(attachmentUrl);
		HttpEntity body = new FileEntity(documentDescription.getImageFile(),
				"image/jpg");
		request.setEntity(body);
		HttpResponse response = new DefaultHttpClient().execute(request);
		HttpEntity entity = response.getEntity();
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.d(TAG, "Created image attachment" + EntityUtils.toString(entity));
	}

}
